package com.paipaideli.wxapi;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;

import com.paipaideli.MyApplication;
import com.paipaideli.common.http.Api;
import com.paipaideli.common.utils.ToastUtil;
import com.paipaideli.common.utils.preferrnces.FastData;
import com.paipaideli.common.views.CommonDialogView;
import com.paipaideli.ui.MainActivity;
import com.paipaideli.ui.mine.head.AssetsActivity;
import com.paipaideli.ui.pay.PayActivity;
import com.paipaideli.wxapi.event.PayEvent;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 支付
 */
public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {

    private IWXAPI api;
    private MyReceiver myReceiver;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        api = WXAPIFactory.createWXAPI(this, "wxf90fd221278b8b0f", false);
        api.handleIntent(getIntent(), this);

        // 在当前的activity中注册广播
        IntentFilter filter = new IntentFilter();
        filter.addAction("ExitActivity2");
        myReceiver = new MyReceiver();
        registerReceiver(myReceiver, filter); // 注册
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq arg0) {

    }

    //广播接收者
    private class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            //当接到广播之后
            finish();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myReceiver);
    }

    @Override
    public void onResp(BaseResp arg0) {
        switch (arg0.errCode) {
            case 0:
                ToastUtil.show("支付成功！");
                EventBus.getDefault().post(new PayEvent());
                getWXQuery();
                finish();
                break;
            case -1:
                ToastUtil.show("支付失败！");
                finish();
                break;
            case -2:
                ToastUtil.show("用户取消了支付！");
                finish();
                break;
            default:
                break;
        }
    }

    private void getWXQuery() {
        JSONObject requestData = new JSONObject();
        try {
            requestData.put("outTradeNo", FastData.getOutTradeNo());
        } catch (Exception e) {
            e.getMessage();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
        Api.getInstanceGson().WXpayQueryPay(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(request -> {
                    if (MyApplication.isAlipay == 1) {
                        MainActivity.openSingleTop(WXPayEntryActivity.this);
                    } else if (MyApplication.isAlipay == 0){
                        Intent intent = new Intent(WXPayEntryActivity.this, AssetsActivity.class);
                        startActivity(intent);
                        finish();
                    }else {
                        final CommonDialogView dialog = new CommonDialogView(WXPayEntryActivity.this);
                        dialog.setMessage("支付成功")
                                .setTitle("温馨提示")
                                .setSingle(true).setOnClickBottomListener(new CommonDialogView.OnClickBottomListener() {
                            @Override
                            public void onPositiveClick() {
                                finish();
                                dialog.dismiss();
                            }

                            @Override
                            public void onNegtiveClick() {
                                dialog.dismiss();

                            }
                        }).show();
                    }
                }, throwable -> {
                });
    }
}
